package com.koron.css2.baseConfig.impl;

import com.koron.css2.AccessoryInterface;
import com.koron.css2.ApplicationConfig;
import com.koron.css2.baseConfig.bean.AccessoryPathBean;
import com.koron.css2.baseConfig.bean.BaseAccessoryMetadataBean;
import com.koron.css2.baseConfig.bean.BaseReceiptAccessoryBean;
import com.koron.css2.baseConfig.mapper.BaseAccessoryMetadataMapper;
import com.koron.css2.baseConfig.mapper.BaseReceiptAccessoryMapper;
import com.koron.css2.common.bean.FileProBean;
import com.koron.css2.common.bean.MultipartContentBean;
import com.koron.css2.common.utils.HttpUtils;
import com.koron.css2.newProjectCenter.function.bean.AccessoryLogBean;
import com.koron.css2.newProjectCenter.function.mapper.AccessoryLogMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.Tools;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.EnvSource;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.http.HttpEntity;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

public class AccessoryImpl implements AccessoryInterface {

    private static Logger log = LogManager.getLogger(AccessoryImpl.class);

    // private static final Map<String, String> FTOKEN = new ConcurrentHashMap<String, String>();

    /***
     * 附件上传
     */
    public MessageBean<?> upload(SessionFactory factory, UserInfoBean userInfo, RequestBean req, List<MultipartFile> files) {
        try {
            BaseReceiptAccessoryBean bean = JsonUtils.objectToPojo(req.getData(), BaseReceiptAccessoryBean.class);
            BaseAccessoryMetadataMapper metadataMapper = factory.getMapper(BaseAccessoryMetadataMapper.class);
            BaseReceiptAccessoryMapper mapper = factory.getMapper(BaseReceiptAccessoryMapper.class);

            if (StringUtils.isBlank(bean.getReceiptId())) {
                return MessageBean.create(Constant.MESSAGE_DBFAIL, "单据主键不能为空", Void.class);
            }
            if (StringUtils.isBlank(bean.getReceiptType())) {
                return MessageBean.create(Constant.MESSAGE_DBFAIL, "单据类型不能为空", Void.class);
            }
            if (StringUtils.isBlank(bean.getAccessoryNo())) {
                return MessageBean.create(Constant.MESSAGE_DBFAIL, "附件类型不能为空", Void.class);
            }
//			if(!"000".equals(bean.getAccessoryNo())) {
//				mapper.deleteByAccessoryNo(bean);
//			}
            List<AccessoryPathBean> pathBeans = new ArrayList<>();
            AccessoryLogMapper accessoryLogMapper = factory.getMapper(AccessoryLogMapper.class,  EnvSource.DEFAULT);
            for (MultipartFile file : files) {
                String path = uploadToLocal(file, accessoryLogMapper, userInfo, bean);
                if (StringUtils.isNotBlank(path)) {

                    BaseAccessoryMetadataBean metadata = new BaseAccessoryMetadataBean();
                    String metadataId = Tools.getObjectId();
                    metadata.setAccessoryPath(path);
                    metadata.setAccessoryName(FilenameUtils.getName(file.getOriginalFilename()));
                    metadata.setId(metadataId);
                    metadata.setAccessorySize(file.getSize());
                    metadata.setAccessoryType(file.getContentType());
                    metadata.setCreateAccount(userInfo.getUserInfo().getAcount());
                    metadata.setCreateName(userInfo.getUserInfo().getName());
                    metadata.setSourceFlag("1");
                    metadataMapper.insert(metadata);

                    // 附件绑定的单据主键ID，如果绑定多个单据，则多个单据的主键ID用逗号分隔
                    String[] receiptIdArray = bean.getReceiptId().split(",", -1);
                    for (String receiptId : receiptIdArray) {
                        String aseReceiptAccessoryId = Tools.getObjectId();
                        bean.setReceiptId(receiptId);
                        bean.setId(aseReceiptAccessoryId);
                        bean.setMetadataId(metadataId);
                        bean.setCreateAccount(userInfo.getUserInfo().getAcount());
                        bean.setCreateName(userInfo.getUserInfo().getName());
                        bean.setAccessoryName(FilenameUtils.getName(file.getOriginalFilename()));
                        mapper.insert(bean);

                        AccessoryPathBean pathBean = new AccessoryPathBean();
                        pathBean.setPath(ApplicationConfig.getAccessoryUploadUrl() + "?path=" + path);
                        pathBean.setId(aseReceiptAccessoryId);
                        pathBeans.add(pathBean);
                    }
                }
            }
            MessageBean<List> data = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "上传附件成功", List.class);
            data.setData(pathBeans);
            return data;
        } catch (Exception e) {
            log.error("附件上传失败：", e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "附件上传失败", null);
        }
    }

    /**
     * 附件下载 待实现.....
     */
    @Override
    public HttpEntity<?> down(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        return null;
    }

    private String upload(MultipartFile file) throws Exception {
        Map<String, String> data = new HashMap<String, String>();
        FileProBean filePro = new FileProBean();
        List<MultipartContentBean> multipartContents = new ArrayList<MultipartContentBean>();
        MultipartContentBean multipartContent = new MultipartContentBean();
        multipartContent.setBytes(file.getBytes());
        multipartContent.setContentType(file.getContentType());
        multipartContent.setFileName(FilenameUtils.getName(file.getOriginalFilename()));
        multipartContents.add(multipartContent);
        String ftoken = getFToken();
        data.put("ftoken", ftoken);
        filePro.setData(data);
        filePro.setMultipart(multipartContents);
        String result = HttpUtils.upload(ApplicationConfig.getAccessoryUploadUrl() + "fileUpload", filePro);
        log.info("文件上传结果返回：{}", result);
        MessageBean<?> message = JsonUtils.jsonToPojo(result, MessageBean.class);
        if (message.getCode() != Constant.MESSAGE_INT_SUCCESS) {
            throw new RuntimeException("文件上传失败：" + message.getDescription());
        }
        Map<String, String> map = JsonUtils.objectToPojo(message.getData(), Map.class);
        return map.get("path");
    }

    private String getFToken() throws Exception {
//		String ftoken = RedisUtils.get("FJftoken");
//		if(StringUtils.isNotBlank(ftoken)) {
//			return ftoken;
//		}
        Map<String, String> data = new HashMap<String, String>();
        data.put("appid", ApplicationConfig.getAccessoryAppId());
        data.put("secret", ApplicationConfig.getAccessorySecret());
        String result = HttpUtils.sendPostJson(ApplicationConfig.getAccessoryUploadUrl() + "fileAuthorize", JsonUtils.objectToJson(data));
        log.info("文件上传获取token结果返回：{}", result);
        MessageBean<?> message = JsonUtils.jsonToPojo(result, MessageBean.class);
        if (message.getCode() != Constant.MESSAGE_INT_SUCCESS) {
            throw new RuntimeException("获取 FTOKEN失败:" + message.getDescription());
        }
        Map<String, String> map = JsonUtils.objectToPojo(message.getData(), Map.class);
//		RedisUtils.setEx("FJftoken", (30 * 60) - 10, map.get("ftoken"));
        return map.get("ftoken");
    }

    private String uploadToLocal(MultipartFile file, AccessoryLogMapper mapper, UserInfoBean userInfo, BaseReceiptAccessoryBean receiptBean) throws Exception {
        // 保存到日志
        String objectId = Tools.getObjectId();
        AccessoryLogBean bean = new AccessoryLogBean();
        bean.setCreateTime(new Date());
        bean.setOriginalFilename(file.getOriginalFilename());
        bean.setId(objectId);
        bean.setCreateAccount(userInfo.getUserInfo().getAcount());
        bean.setCreateName(userInfo.getUserInfo().getName());
        bean.setMyCurrentNodeId(receiptBean.getMyCurrentNodeId());
        bean.setFlowSn(receiptBean.getFlowSn());

        // 拼接文件名，以年月分文件夹存储，并保证文件名不重复
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/");
        String format = sdf.format(new Date());
        String fileName = objectId + "-" + file.getOriginalFilename();
        bean.setFilename(fileName);

        File folder = new File(ApplicationConfig.getFileLocalPath() + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        // 存储文件到本地
        file.transferTo(new File(folder, fileName));
        String path = format + fileName;
        log.info("文件上传成功，文件路径：{}", path);
        bean.setUrl(ApplicationConfig.getAccessoryUploadUrl() + "?path=" + path);
        mapper.insert(bean);
        return format + fileName;
    }

}
